import re

from rest_framework import serializers

from apps.users.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username','mobile','email']


class UserCreateSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField()
    mobile = serializers.CharField()
    email = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate_username(self,value):
        if not re.match(r'^[a-zA-Z0-9]{5,20}$',value):
            raise serializers.ValidationError('用户名为5-20个字符')
        if User.objects.filter(username = value).count()>0:
            raise serializers.ValidationError("用户名已经存在")
        return value
    def validate_mobile(self,value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机格式错误')
        if User.objects.filter(mobile = value).count()>0:
            raise serializers.ValidationError("手机号已经存在")
        return value
    #密码在上面已经验证过

    #重写创建的方法  因为内部里面的create是直接通过用户和密码直接创建用户的 密没有进行加密
    def create(self,validated_data):
        #自定义 将密码进行加密之后再进行保存
        user = User.objects.create_user(**validated_data)
        return user